'use strict';

const db = uniCloud.database();
const collection = db.collection('food-categories');

exports.main = async (event, context) => {
  const { categoryId, updateData } = event.data || {};
  
  if (!categoryId) {
    return {
      code: 400,
      message: '缺少分类ID',
      data: null
    };
  }
  
  if (!updateData || Object.keys(updateData).length === 0) {
    return {
      code: 400,
      message: '缺少更新数据',
      data: null
    };
  }
  
  try {
    // 检查分类是否存在
    const existingCategory = await collection.doc(categoryId).get();
    
    if (!existingCategory.data || existingCategory.data.length === 0) {
      return {
        code: 404,
        message: '分类不存在',
        data: null
      };
    }
    
    // 如果更新名称，检查名称是否重复（排除当前分类）
    if (updateData.name && updateData.name.trim() !== '') {
      const nameCheck = await collection.where({
        name: updateData.name.trim(),
        _id: db.command.neq(categoryId)
      }).get();
      
      if (nameCheck.data.length > 0) {
        return {
          code: 400,
          message: '分类名称已存在',
          data: null
        };
      }
    }
    
    // 准备更新数据
    const updateFields = {};
    
    if (updateData.name !== undefined) {
      updateFields.name = updateData.name.trim();
    }
    if (updateData.description !== undefined) {
      updateFields.description = updateData.description;
    }
    if (updateData.image !== undefined) {
      updateFields.image = updateData.image;
    }
    if (updateData.sort !== undefined) {
      updateFields.sort = updateData.sort;
    }
    if (updateData.status !== undefined) {
      updateFields.status = updateData.status;
    }
    
    // 添加更新时间
    updateFields.update_date = Date.now();
    
    // 执行更新
    const result = await collection.doc(categoryId).update(updateFields);
    
    if (result.updated === 1) {
      // 获取更新后的数据
      const updatedCategory = await collection.doc(categoryId).get();
      
      return {
        code: 200,
        message: '更新成功',
        data: updatedCategory.data
      };
    } else {
      return {
        code: 500,
        message: '更新失败',
        data: null
      };
    }
  } catch (error) {
    console.error('更新菜品分类失败:', error);
    return {
      code: 500,
      message: '更新失败',
      data: null
    };
  }
};